
#include "stdafx.h"
#include "xstrutils.h"
#include "CCharTypes.h"

XUINT32 xstrlen(const XCHAR * pString)
{

	XUINT32 result;
	int currChar;
	XCHAR * pEos;

	if ( pString )
	{
		pEos = (XCHAR * )pString;
		do
		{
			currChar = *pEos;
			++pEos;
		}
		while ( currChar );
		result = pEos - pString - 1;
	}
	else
	{
		result = 0;
	}
	return result;

}

XBOOL xisalpha(XCHAR ch)
{
	XBOOL ret;

	if (ch >= 128 )
		ret = FALSE;
	else
		ret = (XUINT32)(&CCharTypes::s_types)[ch] & 3;
	return ret;

}

XINT32 xstrncmpi(const XCHAR * pTrg, const XCHAR * pSrc, XUINT32 cChar)
{

	XCHAR cchTrg; 
	XCHAR cchSrc;
	int ret;

	while ( cChar )
	{
		if ( xisalpha(*pTrg) && xisalpha(*pSrc) )
		{
			cchTrg = *pTrg;
			cchSrc = *pSrc;
			if ( (XUINT8)(cchTrg & 0xDF) != (XUINT8)(cchSrc & 0xDF) )
				break;
		}
		else
		{
			if ( *pTrg != *pSrc )
				break;
		}
		++pTrg;
		++pSrc;
		--cChar;
	}
	if ( cChar )
		ret = *pTrg - *pSrc;
	else
		ret = 0;
	return ret;

}

XBOOL xisspace(XCHAR ch)
{

	XBOOL ret;

	if ( ch >= 128 )
		ret = FALSE;
	else
		ret = (XUINT32)(&CCharTypes::s_types)[ch] & 8;
	return ret;

}

void * xstrncpy(XCHAR * pTrg, const XCHAR * pSrc, XUINT32 cChar)
{

	XUINT32 v3;
	void *pStart;

	pStart = pTrg;
	while ( TRUE )
	{
		v3 = cChar--;
		if ( !v3 )
			break;
		*pTrg = *pSrc;
		++pTrg;
		++pSrc;
	}
	return pStart;

}

XCHAR * xstritoa(const XUINT32 value, XUINT32 * pcchString)
{

	XUINT32 number = value;
	XUINT32 cchString;
	XINT32 i = 9;
	void *pszString;
	XCHAR buffer[11];

	buffer[10] = 0;

	do
	{
		if ( i < 0 )
			break;
		buffer[i--] = number % 0xA + 48;
		number /= 0xAu;
	}
	while ( number );
	cchString = 10 - (i + 1);

	pszString = new char[2 * (10 - (i + 1) + 1)];
	if ( pszString )
	{
		xstrncpy((XCHAR * )pszString, (const XCHAR * )&buffer[i + 1], cchString);
		*((XCHAR *)pszString + cchString) = NULL;
		if ( pcchString )
			*pcchString = cchString;
	}
	return (XCHAR * )pszString;

}

XCHAR * xstrnistr(const XCHAR * pSrc, const XCHAR * pSub, XUINT32 cChar)
{

	XCHAR v4;
	XCHAR v5;
	bool fMatch;
	XUINT32 cchRemaining;
	const XCHAR * b;
	const XCHAR * a;

ReFind:
	cchRemaining = cChar;
	a = pSrc;
	b = pSub;
	while ( 1 )
	{
		if ( !cchRemaining || !*b )
			return (XCHAR * )pSrc;
		if ( !*a )
			return 0;
		--cchRemaining;
		if ( xisalpha(*a) && xisalpha(*b) )
		{
			v4 = *a;
			v5 = *b;
			fMatch = (XUINT8)(v4 & 223) == (XUINT8)(v5 & 223);
		}
		else
		{
			fMatch = *a == *b;
		}
		++a;
		++b;
		if ( !fMatch )
		{
			++pSrc;
			goto ReFind;
		}
	}

}

XCHAR * xstrnstr(const XCHAR * pSrc, const XCHAR * pSub, XUINT32 cChar)
{

	XINT32 cchb;
	XINT32 ccha;
	XUINT32 cchRemaining; 
	const XCHAR * a;
	const XCHAR * b;

ReFind:
	cchRemaining = cChar;
	a = pSrc;
	b = pSub;
	while ( 1 )
	{
		if ( !cchRemaining || !*b )
			return (XCHAR * )pSrc;
		if ( !*a )
			return 0;
		--cchRemaining;
		cchb = *b;
		ccha = *a;
		++b;
		++a;
		if ( ccha != cchb )
		{
			++pSrc;
			goto ReFind;
		}
	}

}
